package com.calf.cn.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日期工具类
 * 
 * @author guixin
 *
 */
public class DateUtil {

	/**
	 * 将日期转换为字符串
	 * 
	 * @return
	 */
	public static String dateYMD() {
		return dateFormat(new Date(), "yyyy-MM-dd");
	}

	public static String dateFormat() {
		return dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
	}

	public static String dateFormat(String pattern) {
		return dateFormat(new Date(), pattern);
	}

	public static String dateFormat(Date date, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}

	public static Date dateFormat1(Date date, String pattern) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		String source = dateFormat(date, pattern);
		return sdf.parse(source);
	}

	/**
	 * 字符串转换为日期
	 * 
	 * @param source
	 * @return
	 * @throws ParseException
	 */
	public static Date StrToDate(String source, String patten) {
		SimpleDateFormat sdf = new SimpleDateFormat(patten);
		try {
			return sdf.parse(source);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 生成最近几天的日期
	 * 
	 * @param day
	 * @return
	 */
	public static Map<String, Integer> genDate(int day) {
		Map<String, Integer> map = new HashMap<String, Integer>();

		for (int i = 0; i <= day; i++) {
			Calendar calendar = Calendar.getInstance();
			int date = calendar.get(Calendar.DAY_OF_MONTH) - (day - i);

			calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), date);
			String d = dateFormat(calendar.getTime(), "yyyy-MM-dd");
			map.put(d, i);
		}
		return map;
	}

	/**
	 * 生成几天图表的x轴说明
	 * 
	 * @param day
	 * @return
	 */
	public static List<String> genDateArray(int day) {
		List<String> list = new ArrayList<String>();

		for (int i = 0; i <= day; i++) {
			Calendar calendar = Calendar.getInstance();
			int date = calendar.get(Calendar.DAY_OF_MONTH) - (day - i);

			calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), date);
			list.add(dateFormat(calendar.getTime(), "yyyy-MM-dd"));
		}
		return list;
	}

	/**
	 * 判断两个日期是否相等
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 * @throws ParseException
	 */
	public static boolean judgeDateSample(Date date1, Date date2, String patten) throws ParseException {
		date1 = dateFormat1(date1, patten);
		date2 = dateFormat1(date2, patten);
		if (date1.getTime() == date2.getTime())
			return true;
		return false;
	}
}
